import React, { useState } from 'react';
import { Form, Input, Button, Upload, message, Card } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';

const { TextArea } = Input;

function UploadScript() {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);

  const handleUpload = async (values) => {
    const formData = new FormData();
    formData.append('name', values.name);
    formData.append('description', values.description);
    formData.append('content', values.content);
    
    if (fileList.length > 0) {
      formData.append('bgm', fileList[0].originFileObj);
    }

    setUploading(true);

    try {
      const response = await axios.post('http://localhost:5000/api/scripts/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      message.success('上传成功!');
      form.resetFields();
      setFileList([]);
    } catch (error) {
      console.error('Upload failed:', error);
      message.error('上传失败');
    } finally {
      setUploading(false);
    }
  };

  const props = {
    onRemove: (file) => {
      setFileList([]);
    },
    beforeUpload: (file) => {
      setFileList([file]);
      return false;
    },
    fileList,
  };

  return (
    <Card title="上传新剧本" style={{ maxWidth: 600, margin: '0 auto' }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleUpload}
      >
        <Form.Item
          name="name"
          label="剧本名称"
          rules={[{ required: true, message: '请输入剧本名称' }]}
        >
          <Input placeholder="请输入剧本名称" />
        </Form.Item>

        <Form.Item
          name="description"
          label="剧本简介"
        >
          <TextArea rows={4} placeholder="请输入剧本简介" />
        </Form.Item>

        <Form.Item
          name="content"
          label="剧本内容"
          rules={[{ required: true, message: '请输入剧本内容' }]}
        >
          <TextArea rows={10} placeholder="请输入剧本内容" />
        </Form.Item>

        <Form.Item
          name="bgm"
          label="背景音乐(BGM)"
        >
          <Upload {...props} accept="audio/*">
            <Button icon={<UploadOutlined />}>选择BGM文件</Button>
          </Upload>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={uploading}>
            上传剧本
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
}

export default UploadScript;